//  商店页面
//  StoreViewController.m
//  GoBigMarket
//
//  Created by 李真 on 16/8/19.
//  Copyright © 2016年 legend. All rights reserved.
//

#import "StoreViewController.h"
#import "CQCycleView.h"
#import "SDCycleScrollView.h"
#import "ShopModel.h"
#import "StoreCouponsModel.h"
#import "CommodityViewController.h"
#import "StoreViewHeadView.h"
#import "StoreCouponsCell.h"
@interface StoreViewController ()<SDCycleScrollViewDelegate,UITableViewDelegate,UITableViewDataSource>
@property (weak, nonatomic) IBOutlet UITableView *tableView;
@property (nonatomic,strong)NSMutableArray *ShangDianimgArr;
@property (nonatomic,strong)NSMutableArray *couponArr;
@property (nonatomic,strong)StoreViewHeadView *storeViewHeadView;//头视图

@property (weak, nonatomic) IBOutlet UIScrollView *scrollView;
@property (weak, nonatomic) IBOutlet UIView *LBTBackView;//轮播图
@property (weak, nonatomic) IBOutlet UILabel *priceLabel;//起送价label
@property (weak, nonatomic) IBOutlet UILabel *nameLabel;//商店名称
@property (weak, nonatomic) IBOutlet UIView *eventView;//活动view,高度自适应
@property (nonatomic,strong)ShopModel *dataModel;
@property (nonatomic,strong)SDCycleScrollView *LBTView;
@property (nonatomic,strong)MJRefreshNormalHeader *header;
@end

@implementation StoreViewController

- (void)viewDidLoad {
    [super viewDidLoad];

    self.tableView.delegate = self;
    self.tableView.dataSource = self;
    self.tableView.bounces = NO;
    self.tableView.separatorStyle = UITableViewCellSeparatorStyleNone;
}
- (StoreViewHeadView *)storeViewHeadView{
    if (!_storeViewHeadView) {

        _storeViewHeadView = [[[NSBundle mainBundle]loadNibNamed:@"StoreViewHeadView" owner:nil options:nil]lastObject];
    }
    return _storeViewHeadView;
}
#pragma mark - self.tableView.delegate
//点击cell
- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath{
    if (indexPath.section == 0) {
        //领取优惠券
        StoreCouponsModel *model = self.couponArr[indexPath.row];
        [self GetShopCouponsWithCouponId:model.Id WithPrice:model.Price];
    }else{
        //拨打电话
        if (indexPath.row == 2) {
            NSString *str = [NSString stringWithFormat:@"tel://%@",self.dataModel.CompanyPhone];
            NSURL *url = [NSURL URLWithString:str];
            
            UIAlertController *alertController = [UIAlertController alertControllerWithTitle:@"提示" message:@"要拨打商家电话吗?" preferredStyle:UIAlertControllerStyleAlert];
            
            UIAlertAction *centerAction = [UIAlertAction actionWithTitle:@"确定" style:UIAlertActionStyleDefault handler:^(UIAlertAction * _Nonnull action) {
                //拨打电话
                [[UIApplication sharedApplication] openURL:url];
            }];
            
            UIAlertAction *cancelAction = [UIAlertAction actionWithTitle:@"取消" style:UIAlertActionStyleCancel handler:^(UIAlertAction * _Nonnull action) {
                
            }];
            [alertController addAction:centerAction];
            [alertController addAction:cancelAction];
            [self presentViewController:alertController animated:YES completion:^{
                
            }];
        }
    }
}
#pragma mark - 分组头视图
- (nullable UIView *)tableView:(UITableView *)tableView viewForHeaderInSection:(NSInteger)section{
    if (section == 0) {
        return self.storeViewHeadView;
    }else{
        UILabel *storeName = [[UILabel alloc]initWithFrame:CGRectMake(0, 0, XNWindowWidth, 30)];
        storeName.backgroundColor = [UIColor whiteColor];
        storeName.text = @"商店信息";
        return storeName;
    }
}
//分组头视图
- (CGFloat)tableView:(UITableView *)tableView heightForHeaderInSection:(NSInteger)section{
    if (section == 0) {
        return XNWindowWidth / 16 * 9 + 160;
    }else{
        return 30.0f;
    }
}
//分组尾视图
- (CGFloat)tableView:(UITableView *)tableView heightForFooterInSection:(NSInteger)section{
    return 5.0f;
}
//cell高度
- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath{
    if (indexPath.section == 0) {
        return 115;
    }
    return 44;
}
#pragma mark - self.tableView.dataSource
- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView{
    return 2;
}
- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section{
    if (section == 0) {
        //优惠券个数
        return self.couponArr.count;
    }else{
        
        return 3;
    }
    
}

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath{
    if (indexPath.section == 0) {
        //优惠券
        StoreCouponsCell *cell = [tableView dequeueReusableCellWithIdentifier:@"CouponsCellID"];
        if (!cell) {
            cell = [[[NSBundle mainBundle]loadNibNamed:@"StoreCouponsCell" owner:nil options:nil]lastObject];
        }
//        cell.backgroundColor = GDJRandomColor;
        cell.model = self.couponArr[indexPath.row];
        cell.selectionStyle = UITableViewCellSelectionStyleNone;
        return cell;
    }else{
        
        UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:@"shangdianxinxiCellD"];
        if (!cell) {
            cell = [[UITableViewCell alloc]initWithStyle:UITableViewCellStyleDefault reuseIdentifier:@"shangdianxinxiCellD"];
        }
        //设置图片
//        cell.imageView.image = [UIImage imageNamed:self.ShangDianimgArr[indexPath.row]];
        if (FourInch) {
            cell.textLabel.font = [UIFont systemFontOfSize:15.0f];
        }
        //设置内容
        switch (indexPath.row) {
            case 0:
                cell.textLabel.text = [NSString stringWithFormat:@"营业时间：%@",self.dataModel.YingYeRQ];
                break;
            case 1:
                cell.textLabel.numberOfLines = 0;
                cell.textLabel.attributedText = [self strFontAndSizeWithStr:[NSString stringWithFormat:@"商店地址：%@",self.dataModel.CompanyAddress]];
                break;
            case 2:
                cell.textLabel.text = [NSString stringWithFormat:@"电话号码：%@", self.dataModel.CompanyPhone];
                break;
            default:
                break;
        }

        cell.selectionStyle = UITableViewCellSelectionStyleNone;
        return cell;
    }
    
}


//#pragma mark - 视图高度自动
//-(void)viewDidLayoutSubviews{
//    [super viewDidLayoutSubviews];
//    
//    CGRect frame =[self.detailsLabel.text boundingRectWithSize:CGSizeMake(XNWindowWidth, 9999) options:NSStringDrawingUsesLineFragmentOrigin attributes:@{NSFontAttributeName:[UIFont systemFontOfSize:17]} context:nil];
//    self.detailsLabel.height = frame.size.height;
//}
#pragma mark - 周期
-(void)viewDidAppear:(BOOL)animated{
    [super viewDidAppear:animated];
}

-(void)viewWillAppear:(BOOL)animated{
    [super viewWillAppear:animated];
    if (!self.ShangDianimgArr) {
        self.ShangDianimgArr = [NSMutableArray arrayWithObjects:@"store_address",@"store_time",@"store_phone", nil];
    }
    if (!_couponArr) {
        _couponArr = [NSMutableArray array];
    }
   
    [self netWorking];
    self.dataModel = [[ShopModel alloc]init];
    self.tabBarController.tabBar.hidden = YES;
}
-(void)viewDidDisappear:(BOOL)animated{
    [super viewDidDisappear:animated];
}
#pragma mark - 网络请求
- (void)netWorking{
   
    [CQNetWorkTools GETWithURL:GetStoreD par:@{@"ShopId":GETShopId} success:^(id responseObject) {
        DLog(@"商店详情__%@",responseObject);
        if ([[responseObject valueForKey:@"Err"]integerValue] != 0 ) {
            //不成功,打印错误信息
            [SVProgressHUD  showWithStatus:[responseObject objectForKey:@"ErrMsg"]];
            [SVProgressHUD dismiss];
            
        }else{
            //成功
            self.dataModel = [ShopModel mj_objectWithKeyValues:[responseObject valueForKey:@"Shop"]];
            self.navigationItem.title = self.dataModel.ShopName;
            [self fillData];
           
            [self.tableView reloadData];
        }
        
    } filed:^(NSError *error) {
        
    }];
    //获取优惠券
    [CQNetWorkTools GETWithURL:GetChaKanYHJ par:@{@"ShopId":GETShopId,@"ShouJiHao":GETPHONE,@"Token":GETTOKEN,@"Duuid":GETUUID} success:^(id responseObject) {
        DLog(@"商店红包列表__ %@",responseObject);
        if ([[responseObject objectForKey:@"Err"]integerValue]) {
            
        }else{
            NSDictionary *dic = [responseObject objectForKey:@"Coupons"];
            _couponArr = [StoreCouponsModel mj_objectArrayWithKeyValuesArray:dic];
        }
        //成功后刷新
        [self.tableView reloadSections:[NSIndexSet indexSetWithIndex:0] withRowAnimation:UITableViewRowAnimationFade];
    } filed:^(NSError *error) {
        
        
    }];
}
#pragma mark - 领优惠券
- (void)GetShopCouponsWithCouponId:(NSString *)CouponId WithPrice:(NSString *)price{
   
    [CQNetWorkTools POSTWithURL: PostLingQuYHJ par:@{@"ShopId":GETShopId,@"ShouJiHao":GETPHONE,@"Token":GETTOKEN,@"Duuid":GETUUID,@"CouponId":CouponId} success:^(id responseObject) {
        DLog(@"领取红包_success_ %@",responseObject);
        NSString *title;//标题
        NSString *text = [NSString stringWithFormat:@"恭喜获得%@优惠券",price];//message
        if ([[responseObject objectForKey:@"Err"] integerValue]) {
            title = @"领取失败!";
            text = [responseObject objectForKey:@"ErrMsg"];
        }else{
            title = @"领取成功!";
        }
        
        UIAlertView *alertView = [[UIAlertView alloc]initWithTitle:title message:text delegate:self cancelButtonTitle:@"好的" otherButtonTitles:nil];
        [alertView show];
        
    } filed:^(NSError *error) {
        DLog(@"领取红包_error_%@",error);
        
    }];
}
#pragma mark - 加载数据
- (void)fillData{
    self.storeViewHeadView.nameLabel.attributedText = [self strSuoJinWithStr:self.dataModel.ShopName];
    self.storeViewHeadView.QSLabel.attributedText = [self strColorAndSizeWithStr:[NSString stringWithFormat:@"起送价:%d元",self.dataModel.QiSongJia]];

    //创建LBTView
    [self creatLBTView];
}
#pragma mark - 轮播图创建
- (void)creatLBTView{
    if (!self.LBTView) {
        self.LBTView = [SDCycleScrollView cycleScrollViewWithFrame:CGRectMake(0, 0, XNWindowWidth, XNWindowWidth / 16 * 9) delegate:self placeholderImage:nil];
    }
    //刷新轮播图
    NSMutableArray *arr = [NSMutableArray array];
    for (NSString *str in self.dataModel.ImgUrl) {
        [arr addObject:[NSString stringWithFormat:@"%@%@",ReleaseORDebug,str]];
    }
    self.LBTView.showPageControl = YES;
    self.LBTView.currentPageDotColor = [UIColor whiteColor];
    self.LBTView.imageURLStringsGroup = arr;
    self.LBTView.showPageControl = YES;
    self.LBTView.backgroundColor = [UIColor whiteColor];
    [self.storeViewHeadView.LBTView addSubview: self.LBTView];
}
#pragma mark - 富文本设置
//字体变色
- (NSAttributedString *)strColorAndSizeWithStr:(NSString *)str{
    //售价
    NSMutableAttributedString *attributedString = [[NSMutableAttributedString alloc] initWithString:str];
    [attributedString addAttribute:NSForegroundColorAttributeName value:GDJColor(236, 152, 18) range:NSMakeRange(4, str.length - 5)];
    [attributedString addAttribute:NSFontAttributeName value:[UIFont systemFontOfSize:22] range:NSMakeRange(4, str.length - 5)];
    
    return attributedString;
}
//缩小字体
- (NSAttributedString *)strFontAndSizeWithStr:(NSString *)str{
    //售价
    NSMutableAttributedString *attributedString = [[NSMutableAttributedString alloc] initWithString:str];        [attributedString addAttribute:NSFontAttributeName value:[UIFont systemFontOfSize:13] range:NSMakeRange(4, str.length - 4)];
    return attributedString;
}
//行缩进
- (NSAttributedString *)strSuoJinWithStr:(NSString *)str{
    
    NSMutableParagraphStyle *paraStyle01 = [[NSMutableParagraphStyle alloc] init];
    paraStyle01.alignment = NSTextAlignmentLeft;  //对齐
    paraStyle01.headIndent = 0.0f;//行首缩进
    //参数：（字体大小17号字乘以2，34f即首行空出两个字符）
    CGFloat emptylen = 10.0f;
    paraStyle01.firstLineHeadIndent = emptylen;//首行缩进
    paraStyle01.tailIndent = 10.0f;//行尾缩进
    paraStyle01.lineSpacing = 2.0f;//行间距
    
    NSAttributedString *attrText = [[NSAttributedString alloc] initWithString:str attributes:@{NSParagraphStyleAttributeName:paraStyle01}];
    
    return attrText;
}
@end
